﻿using System.Net;
using System.Net.Mail;
using System.Text;

namespace DearLee.Toolkit {

  public class Email {

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="from">发信人地址</param>
    /// <param name="displayName">与发信人地址关联的显示名，可为 null</param>
    /// <param name="host">STMP 事务的主机或 IP 地址</param>
    /// <param name="username">发信人邮箱登录名</param>
    /// <param name="password">发信人邮箱密码</param>
    public Email(string from, string displayName, string host, string username, string password) {

      From = from;
      DisplayName = displayName;
      Host = host;
      Username = username;
      Password = password;
    }

    /// <summary>
    /// 发信人地址
    /// </summary>
    public string From { get; set; }

    /// <summary>
    /// 与发信人地址关联的显示名，可为 null
    /// </summary>
    public string DisplayName { get; set; }

    /// <summary>
    /// STMP 事务的主机或 IP 地址
    /// </summary>
    public string Host { get; set; }

    /// <summary>
    /// 发信人邮箱登录名
    /// </summary>
    public string Username { get; set; }

    /// <summary>
    /// 发信人邮箱密码
    /// </summary>
    public string Password { get; set; }

    /// <summary>
    /// 发送邮件
    /// </summary>
    /// <param name="to">收信人地址</param>
    /// <param name="subject">主题</param>
    /// <param name="body">正文</param>
    /// <param name="isBodyHtml">正文是否为 ＨＴＭＬ</param>
    public void SendMail(string to, string subject, string body, bool isBodyHtml) {

      MailMessage message = null;
      SmtpClient client = null;
      object userToken = null;

      message = new MailMessage {
        From = new MailAddress(From, DisplayName),
        Subject = subject,
        Body = body,
        SubjectEncoding = Encoding.UTF8,
        BodyEncoding = Encoding.UTF8,
        IsBodyHtml = isBodyHtml,
        Priority = MailPriority.Normal
      };

      message.To.Add(to);

      client = new SmtpClient();
      client.Host = Host;
      client.Credentials = new NetworkCredential(Username, Password);
      userToken = message;

      client.Send(message);
    }
  }
}
